@CI
3年前 提问
1个回答

c++读取txt文件

一颗小胡椒
3年前

代码如下:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    //创建二维数组分别存储int及string数据
    string str[25][4];
    int I[25][2] = {0};
    ifstream myfile("data1.txt");
    ofstream outfile("out.txt", ios::trunc);

    if (!myfile.is_open())
    {
        cout << "can not open this file" << endl;
        return 0;
    }
    //从data1文件中读入int数据
    for (int i = 0; i < 25; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            myfile >> I[i][j];
        }
    }
    //读入string数据
    for (int i = 25; i < 50; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            myfile >> str[i-25][j];
        }
    }
    //将数据输出至out.txt文件中
    for (int i = 0; i < 25; i++)
    {
        outfile  << I[i][0] << "    " << I[i][1] << "    "
            << str[i][0] << "    " << str[i][1] << "    "
            << str[i][2] << "    " << str[i][3]<< endl;
    };

    myfile.close();
    outfile.close();
    return 0;
}